package com.cdvtc.news.service.impl;

import com.cdvtc.news.dao.NewsDao;
import com.cdvtc.news.entity.News;
import com.cdvtc.news.service.NewsService;
import com.cdvtc.news.service.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao newsDao;

    @Override
    public List<News> getNews(Integer categoryId, Integer tagId) {
        List<News> newsList;
        if(categoryId != null) {
            newsList = newsDao.getNewsByCategory(categoryId);
        } else if(tagId != null) {
            newsList = newsDao.getNewsByTag(tagId);
        } else {
            newsList = newsDao.getStickNews(10); //默认查询置顶（首页）新闻
        }
        return newsList;
    }

    @Override
    public News getNewsById(int newsId) {
        return newsDao.getNewsById(newsId);
    }

    @Override
    public List<News> getRecommendedNews(int newsId) {
        return newsDao.getRecommendedNews(newsId);
    }

    @Override
    public List<News> getStickNews(int limit) {
        return newsDao.getStickNews(limit);
    }

    @Override
    public List<News> getHotNews() {
        return newsDao.getHotNews();
    }

    @Override
    public void updateClickCount(int newsId) {
        newsDao.updateClickCount(newsId);
    }

    @Override
    public List<Map<String, Object>> statNewsCountByCategory() {
        return newsDao.statNewsCountByCategory();
    }

    @Override
    public List<Map<String, Object>> statNewsCountByTag() {
        return newsDao.statNewsCountByTag();
    }

    @Override
    public List<Map<String, Object>> statNewsCommentCountByDate() {
        return newsDao.statNewsCommentCountByDate();
    }

    @Override
    public List<Map<String, Object>> statNewsCommentCountByUser() {
        return newsDao.statNewsCommentCountByUser();
    }

    @Override
    public Page<News> getPagedNews(Integer pageNumer, Integer pageSize) {
        // 校正参数
        if (pageNumer == null || pageNumer < 1) {
            pageNumer = 1;
        }
        if (pageSize ==  null || pageSize < 1) {
            pageSize = 10;
        }

        // 初始化分页对象
        PageImpl<News> page = new PageImpl<>();
        page.setPageNumber(pageNumer);
        page.setPageSize(pageSize);

        PageHelper.offsetPage((pageNumer-1)*pageSize, pageSize); // 使用分页插件
        page.setPagedData(newsDao.getAllNews());
        page.setTotalRows(newsDao.getNewsTotal());
        return page;
    }

    @Override
    public Integer addNews(News news) {
        return newsDao.addNews(news);
    }

    @Override
    public void updateNews(News news) {
        newsDao.updateNews(news);
    }
}
